<?php

class phpinchains_util_XMLSerializer {

    public static function serialize ($struct, $rootelement) {
        $xml = '<'.$rootelement.'>';
        $xml .= self::serialize_hlp($struct);
        $xml .= '</'.$rootelement.'>';
        return $xml;
    }

    private static function serialize_hlp ($struct, $name = '') {
        $xml = "";
        // if is not an array it already is "serialized"
        if (!is_array($struct)) {
            return "<![CDATA[$struct]]>";
        }
        if ($name == '')
            $name = 'item';
        if (isset($struct[0])) {
            for ($i = 0; $i < count($struct); $i++) {
                $xml .= '<'.$name.'>'.self::serialize_hlp($struct[$i]).'</'.$name.'>';
            }
        } elseif (!is_array($struct)) {
            $xml = $struct;
        } else {
            foreach ($struct as $n => $v) {

                $xml .= '<'.$n.'>'.self::serialize_hlp($v).'</'.$n.'>';
            }
        }
        return $xml;
    }



    public static function serializeE4X ($struct, $rootelement) {
        $xml = '<'.$rootelement.(is_array($struct)?self::serializeAttributes($struct):'').'>';
        $xml .= self::serializeE4X_hlp($struct, $rootelement);
        $xml .= '</'.$rootelement.'>';
        return $xml;
    }

    private static function serializeE4X_hlp ($struct, $name = '') {
        $xml = "";
        if (!is_array($struct)) {
            return $struct;
        }
        if ($name == '')
            $name = 'item';
        if (isset($struct[0])) {
            for ($i = 0; $i < count($struct); $i++) {
                $xml .= "\n".'<'.$name.(is_array($struct[$i])?self::serializeAttributes($struct[$i]):'').'>'.self::serializeE4X_hlp($struct[$i]).'</'.$name.'>'."\n";
            }
        } elseif (!is_array($struct)) {
            $xml = $struct;
        } else {
        //$xml .= '<'.$name.(is_array($struct)?self::serializeAttributes($struct):'').'>';
            foreach ($struct as $n => $v) {
                if ($n{0} != '@') {
                    if (isset($v[0])) {
                        $xml .= self::serializeE4X_hlp($v, $n);
                    } else {
                        $xml .= "\n".'<'.$n.(is_array($v)?self::serializeAttributes($v):'').'>'.self::serializeE4X_hlp($v, $n).'</'.$n.'>'."\n";
                    }
                }
            }
        //$xml .= '</'.$name.'>';
        }
        return $xml;
    }

    private static function serializeAttributes ($struct) {
        foreach ($struct as $n => $v) {
            if ($n{0} == '@')
                $xml .= ' '.substr($n, 1).'="'.$v.'"';
        }
        return $xml;
    }

}

?>